package net.huashitong.supervision.appController;

import com.sirdc.modules.core.exceptions.ServiceException;
import com.sirdc.modules.core.exceptions.UserExistException;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.filter.DeptFilter;
import com.sirdc.modules.sys.filter.SysDeptFilter;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.DeptService;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.sirdc.modules.utils.date.DateUtils;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.LogFilter;
import net.huashitong.supervision.task.filter.TaskMainFilter;
import net.huashitong.supervision.task.filter.TaskUnitFilter;
import net.huashitong.supervision.task.service.*;
import net.huashitong.supervision.task.util.RoleMenuUtilsService;
import net.huashitong.supervision.task.util.WeekDayUtil;
import net.huashitong.util.UtilsTools;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2020/1/10
 * Time: 9:51
 * To change this template use File | Settings | File Templates.
 * Description: 管理员ctrl
 */
@Controller
@RequestMapping(value = "/appAdmin")
public class AppAdminController extends JsonBaseController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private RoleMenuUtilsService roleMenuUtilsService;
    @Autowired
    private DeptService deptService;
    @Lazy
    @Autowired
    private TaskMainService taskMainService;
    @Autowired
    private TaskUnitService taskUnitService;
    @Autowired
    private TaskCategoryService taskCategoryService;
    @Autowired
    private TaskLogEntityService taskLogEntityService;
    @Autowired
    private TaskCategoryLogService taskCategoryLogService;
    @Autowired
    private SysDeptLogService sysDeptLogService;
    @Autowired
    private TaskBackNewService taskBackNewService;
    @Autowired
    private SMSLogService smsLogService;
    @Autowired
    private AppLoginLogService appLoginLogService;
    @Autowired
    private OrderScoreService orderScoreService;
    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 用户管理列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sysUserList", method = RequestMethod.POST)
    public Message sysUserList(@RequestBody SysUserFilter filter) {
        try {
            List<SysUserDataBean> sysUserDataBeans = sysUserService.queryOnDatabean(filter);
            return coverMessage("200", "用户列表", sysUserDataBeans);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 用户详情
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userDetail", method = RequestMethod.POST)
    public Message userDetail(@RequestBody SysUserDataBean dataBean) {
        try {
            if (StringUtils.isNotBlank(dataBean.getSysId())) {
                SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(dataBean.getSysId());
                return coverMessage("200", "用户详情", userDataBean);
            } else {
                return coverMessage("500", "error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 当前所有单位列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deptList", method = RequestMethod.POST)
    public Message deptList(@RequestBody SysDeptFilter filter) {
        try {
            List<SysDept> deptList = new ArrayList<>();
            List<SysDept> depts = deptService.queryByDeptLevel(3);
            List<SysDept> dcDepts = deptService.queryDeptList("/01/");
            deptList.addAll(dcDepts);
            deptList.addAll(depts);
            if (ObjectUtils.isNotBlank(deptList)) {
                return coverMessage("200", "单位列表", deptList);
            } else {
                return coverMessage("500", "error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 添加修改用户
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editUser", method = RequestMethod.POST)
    public Message editUser(@RequestBody SysUserDataBean dataBean) {
        try {
            if (StringUtils.isNotBlank(dataBean.getSysId())) {
                //修改
                dataBean.setUserId(dataBean.getSysId());
                sysUserService.updateUserLogin(dataBean);
                return coverMessage("200", "修改成功");

            } else {
                //新增
                try {
                    sysUserService.saveUserLogin(dataBean);
                    return coverMessage("200", "保存成功");
                } catch (UserExistException ue) {
                    return coverMessage("500", "用户名已存在");
                } catch (Exception e) {
                    e.printStackTrace();
                    return coverMessage("500", e.getMessage());
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 删除用户
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delUser", method = RequestMethod.POST)
    public Message delUser(@RequestBody SysUserDataBean dataBean) {
        try {
            if (StringUtils.isNotBlank(dataBean.getSysId())) {
                if (dataBean.getSysId().equals(UtilsTools.SysUserId)) {
                    return coverMessage("500", "您不能删除自己");
                } else {
                    List<String> ids = new ArrayList<>();
                    ids.add(dataBean.getSysId());
                    sysUserService.batchDelete(ids);
                    return coverMessage("200", "删除成功");
                }
            } else {
                return coverMessage("500", "error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 编辑/新增单位
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editDept")
    public Message editDept(@RequestBody DeptFilter filter) {
        try {
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(filter.getUserId());
            if (StringUtils.isNotBlank(filter.getSysId())) {
                //修改
                SysDept dept = deptService.getById(filter.getSysId());
                if (filter.getDeptRelation().equals("/01/")) {
                    dept.setDeptLevel(2);
                } else {
                    dept.setDeptLevel(3);
                }
                dept.setDeptRelation(filter.getDeptRelation());
                dept.setDeptName(filter.getDeptName());
                SysDeptLog sysDeptLog = new SysDeptLog();
                sysDeptLog.setDateTime(DateUtils.getDateTime());
                sysDeptLog.setUserId(filter.getUserId());
                sysDeptLog.setUserName(dataBean.getUsername());
                sysDeptLog.setIp(filter.getIp());
                sysDeptLog.setDeptId(filter.getSysId());
                sysDeptLog.setType("1");//修改
                sysDeptLog.setDeptName(dept.getDeptName());
                sysDeptLog.setContent("修改单位");
                sysDeptLogService.save(sysDeptLog);
                deptService.update(dept);
                return coverMessage("200", "成功");
            } else {
                //新增
                SysDept sysDept = new SysDept();
                BeanUtils.copyProperties(filter, sysDept);
                if (filter.getDeptRelation().contains("/01/")) {
                    sysDept.setDeptLevel(2);
                } else {
                    sysDept.setDeptLevel(3);
                }
                sysDept.setState("02");
                sysDeptService.save(sysDept);
                SysDeptLog sysDeptLog = new SysDeptLog();
                sysDeptLog.setDateTime(DateUtils.getDateTime());
                sysDeptLog.setUserId(filter.getUserId());
                sysDeptLog.setUserName(dataBean.getUsername());
                sysDeptLog.setIp(filter.getIp());
                sysDeptLog.setDeptId(sysDept.getSysId());
                sysDeptLog.setType("2");//新增
                sysDeptLog.setDeptName(sysDept.getDeptName());
                sysDeptLog.setContent("新增单位");
                sysDeptLogService.save(sysDeptLog);

                filter.setSysId(sysDept.getSysId());
                String s = roleMenuUtilsService.addDeptRoleMenu(filter);
                if ("200".equals(s)) {
                    return coverMessage("200", "成功");
                } else {
                    return coverMessage("500", "error");
                }
            }
        } catch (BeansException e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 删除单位
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delDept", method = RequestMethod.POST)
    public Message delDept(@RequestBody DeptFilter filter) {
        try {
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(filter.getUserId());

            String sysId = filter.getSysId();
            SysDept dept = deptService.getById(sysId);
            List<String> ids = new ArrayList<>();

            SysDeptLog sysDeptLog = new SysDeptLog();
            sysDeptLog.setDateTime(DateUtils.getDateTime());
            sysDeptLog.setUserId(filter.getUserId());
            sysDeptLog.setUserName(dataBean.getUsername());
            sysDeptLog.setIp(filter.getIp());
            sysDeptLog.setDeptId(dept.getSysId());
            sysDeptLog.setType("0");//删除
            sysDeptLog.setDeptName(dept.getDeptName());
            sysDeptLog.setContent("删除单位");
            sysDeptLogService.save(sysDeptLog);
            ids.add(sysId);
            this.sysDeptService.batchDeleteWithChild(ids);
            this.sysDeptService.refreshCache();
            return this.coverMessage("200", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 所有任务列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/allTask", method = RequestMethod.POST)
    public Message allTask(@RequestBody TaskMainFilter filter) {
        try {
            String sysUserId = UtilsTools.SysUserId;
            List<TaskMain> taskMainList = taskMainService.queryFilter(filter);
            System.out.println(taskMainList.size());
            return coverMessage("200", "任务列表", taskMainList);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/taskLogList", method = RequestMethod.POST)
    public Message taskLogList(@RequestBody LogFilter filter) {
        try {
            List<TaskLogEntity> query = taskLogEntityService.queryFilter(filter);
            if (ObjectUtils.isNotBlank(query)) {
                return coverMessage("200", "任务日志", query);
            } else {
                return coverMessage("500", "无日志");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/categoryLogList", method = RequestMethod.POST)
    public Message categoryLogList(@RequestBody LogFilter filter) {
        try {
            List<TaskCategoryLog> query = taskCategoryLogService.queryFilter(filter);
            if (ObjectUtils.isNotBlank(query)) {
                return coverMessage("200", "事项日志", query);
            } else {
                return coverMessage("500", "无日志");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }
    @ResponseBody
    @RequestMapping(value = "/deptLogList", method = RequestMethod.POST)
    public Message deptLogList(@RequestBody LogFilter filter) {
        try {
            List<SysDeptLog> query = sysDeptLogService.queryFilter(filter);
            if (ObjectUtils.isNotBlank(query)) {
                return coverMessage("200", "单位日志", query);
            } else {
                return coverMessage("500", "无日志");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/homeInfo",method = RequestMethod.POST)
    public Message homeInfo(@RequestBody SysUserDataBean dataBean){
        try {
            //当前查询时间日期
            String date = DateUtils.getDate();
            TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
            //7天前的日期
            String pastDate = WeekDayUtil.getPastDate(7);
            taskUnitFilter.setCreateDate(pastDate);
            //7天内生成的单位任务
            List<TaskUnit> taskUnits = taskUnitService.queryDateFilter(taskUnitFilter);
            //7天内反馈的记录
            List<TaskBackNew> taskBackNews=taskBackNewService.queryBeforeDate(pastDate);
            //7天内发送的短信记录
            List<SMSLogEntity>smsLogEntities= smsLogService.queryBeforeDate(pastDate);
            Map<String ,Object> resultMap= new HashMap<>();
            resultMap.put("taskUnit", taskUnits.size());
            resultMap.put("taskBack", taskBackNews.size());
            resultMap.put("smsLog", smsLogEntities.size());
            return coverMessage("200","success",resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500",e.getMessage());
        }
    }

    /**
     * app 登录日志记录列表
     * @param loginLog
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/loginLogList",method = RequestMethod.POST)
    public Message appLoginLogList(@RequestBody AppLoginLog loginLog){
        List<Map<String, Object>> mapList = appLoginLogService.queryList(loginLog);
        if (ObjectUtils.isNotBlank(mapList)){
            return coverMessage("200","登录日志列表",mapList);
        }else{
            return coverMessage("500","error");
        }
    }

    @Autowired
    private ScoreLevelService scoreLevelService;
    /**
     * 评分等级列表
     * @param scoreLevel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/scoreLevelList",method = RequestMethod.POST)
    public Message scoreLevelList(@RequestBody ScoreLevel scoreLevel){
        try {
            List<ScoreLevel> list = scoreLevelService.query();
            return coverMessage("200","评分等级列表",list);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500",e.getMessage());
        }
    }

    /**
     * 新增/修改评分等级
     * @param scoreLevel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editScoreLevel",method = RequestMethod.POST)
    public Message editScoreLevel(@RequestBody ScoreLevel scoreLevel){
        try {
            if (StringUtils.isNotBlank(scoreLevel.getSysId())){
                //修改
                scoreLevelService.update(scoreLevel);
            }else{
                //新增
                scoreLevelService.save(scoreLevel);
            }
            return coverMessage("200","操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500",e.getMessage());
        }
    }

    /**
     * 删除评分规则
     * @param scoreLevel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delScoreLevel",method = RequestMethod.POST)
    public Message delScoreLevel(@RequestBody ScoreLevel scoreLevel) {
        try {
            scoreLevelService.delete(scoreLevel);
            return coverMessage("200","删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500","删除失败:"+e.getMessage());
        }
    }

    /**
     * 排序得分规则
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "editOrderScore",method = RequestMethod.POST)
    public Message editOrderScore(@RequestBody OrderScore orderScore){
        try {
            if (StringUtils.isNotBlank(orderScore.getSysId())){
                //编辑
                OrderScore orderScoreServiceById = orderScoreService.getById(orderScore.getSysId());
                if (StringUtils.isNotBlank(orderScore.getOrderScoreJson())){
                    orderScoreServiceById.setOrderScoreJson(orderScore.getOrderScoreJson());
                    List<OrderScore> query = orderScoreService.query();
                    // 将所有规则先设为未启用
                    query.forEach(entity->{
                        entity.setState("0");
                        orderScoreService.update(entity);
                    });
                    //启用当前编辑规则
                    orderScoreServiceById.setState("1");//启用
                    orderScoreService.update(orderScoreServiceById);
                }
            }else{
            //    新增
                orderScore.setState("0");
                orderScoreService.save(orderScore);
            }
            return coverMessage("200","success");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500",e.getMessage());
        }
    }
}
